<template>
  <SuperTable :data-request="fetchData" :columns="baseColumns" header-title="审批管理" pager align="center" border
    ref="supertable" :export-config="{}">
    <template #action>
      <a-button type="primary" @click="visibleloading = true">新增业务流程</a-button>
    </template>
  </SuperTable>
  <a-drawer destroyOnClose :footerStyle="{ display: 'flex', justifyContent: 'center' }" :title="title" width="40%"
    :visible="visibleloading" @close="onClose">
    <a-form ref="dynamicFormRef" :model="subdata" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 10 }"
      autocomplete="off">
      <a-form-item label="业务流程名称" name="processName" :rules="[{ required: true, message: '业务流程名称不能为空!' }]">
        <a-input placeholder="请输入业务流程名称" v-model:value="subdata.processName" />
      </a-form-item>
    </a-form>
    <a-tabs type="card" v-model:activeKey="activeKey" tab-position="left" animated>
      <!-- <a-tab-pane key="1" tab="样本登记">
        <order @change="switchChange" v-for="item in tabdata.registration" :key="item.order" :item="item" :length="tabdata.registration.length"></order>
      </a-tab-pane> -->
      <a-tab-pane key="2" tab="样本入库">
        <order @change="switchChange" v-for="item in tabdata.in" :key="item.order" :item="item"
          :length="tabdata.in.length"></order>
      </a-tab-pane>
      <a-tab-pane key="3" tab="样本出库">
        <order @change="switchChange" v-for="item in tabdata.out" :key="item.order" :item="item"
          :length="tabdata.out.length"></order>
      </a-tab-pane>
      <a-tab-pane key="7" tab="库存盘点">
        <order @change="switchChange" v-for="item in tabdata.Inventory" :key="item.order" :item="item"
          :length="tabdata.Inventory.length"></order>
      </a-tab-pane>
    </a-tabs>
    <template #footer>
      <a-button style="margin-right: 15px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="submit">保存</a-button>
    </template>
  </a-drawer>
  <a-drawer destroyOnClose :footerStyle="{ display: 'flex', justifyContent: 'center' }" title="配置样本类型" width="40%"
    :visible="configuration" @close="onClose">
    <div style="height: 100%">
      <a-transfer :list-style="{
        width: '300px',
        border: 0,
      }" show-search v-model:target-keys="targetKeys" class="tree-transfer" :data-source="dataSource"
        :render="(item) => item.title" :filter-option="filterOption" @search="transferSearch" @change="transferChange">
        <template #children="{ direction, selectedKeys, onItemSelect }">
          <a-tree v-if="direction === 'left'" block-node checkable default-expand-all
            :checked-keys="[...selectedKeys, ...targetKeys]" :tree-data="treeData" @check="(_, props) => {
              onChecked(props, [...selectedKeys, ...targetKeys], onItemSelect);
            }
              " @select="(_, props) => {
    onChecked(props, [...selectedKeys, ...targetKeys], onItemSelect);
  }
    " />
        </template>
      </a-transfer>
    </div>
    <template #footer>
      <a-button style="margin-right: 15px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="submit2">保存</a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="tsx">
import { ref, reactive, computed } from 'vue';
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import { getList, getAddList, getPutList, getDelList, gettypeList } from '../../api/sampleProcessList';
import columns, { TableColumnList } from './columns';
import { message, Modal } from 'ant-design-vue';
import order from '../../components/order.vue';
import { VxeGridPropTypes } from 'vxe-table';
import _ from 'lodash-es';
const supertable = ref();
const dynamicFormRef = ref();
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let queryparams: any = {
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    orderBy: [
      {
        field: 'createTime',
        order: 'desc',
      },
    ],
    paging: false,
  };
  let { result } = await getList(queryparams);
  return result;
};
let id = 0;
let title = ref('新增业务流程')
let baseColumns: TableColumnList = [
  ...columns,
  {
    title: '操作',
    field: '$action',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 300,
    actions: ({ row }) => [
      {
        label: '配置',
        onClick: async () => {
          getSampType({ id: row.id, processName: row.processName }, row);
          subdata.processName = row.processName;
          activeKey.value = '2';
          subdata.dataLink = row.dataLink;
          subdata.dataLink.forEach(item => {
            tabdata[enumeration[item.processType]].forEach(el => {
              if (el.name == '上传存档文件') el.switch = item.isArchive;
              if (el.name == '高拍仪拍摄') el.switch = item.isCapture;
              if (el.name == '电子签名') el.switch = item.isSignature;
            })
          });
          configuration.value = true;
          id = row.id;
        },
      },
      {
        label: '编辑',
        onClick: async () => {
          title.value = '编辑业务流程'
          subdata.processName = row.processName;
          activeKey.value = '2';
          row.dataLink.forEach(item => {
            tabdata[enumeration[item.processType]].forEach(el => {
              if (el.name == '上传存档文件') el.switch = item.isArchive;
              if (el.name == '高拍仪拍摄') el.switch = item.isCapture;
              if (el.name == '电子签名') el.switch = item.isSignature;
            })
          });
          console.log(tabdata, 998877);
          visibleloading.value = true;
          id = row.id;
        },
      },
      {
        label: '删除',
        onClick: async () => {
          Modal.confirm({
            title: '确认删除吗?',
            onOk: async () => {
              await getDelList(row.id);
              supertable.value?.refreshTable();
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        },
      },
    ],
  },
];
const visibleloading = ref(false);
const configuration = ref(false);
const onClose = () => {
  id = 0;
  visibleloading.value = false;
  dynamicFormRef.value?.resetFields();
  configuration.value = false;
  activeKey.value = '2';
  targetKeys.value = [];
  dataSource.value = [];
  subdata.processName = ''
  subdata.specimenType = ''
  subdata.dataLink = []
  tabdata.out.forEach((item) => (item.switch = true));
  tabdata.in.forEach((item) => (item.switch = true));
  tabdata.Inventory.forEach((item) => (item.switch = true));
  title.value = '新增业务流程'
};
const activeKey = ref('2');
const tabdata = reactive({
  in: [
    { order: 1, name: '新建入库单', isshow: false, switch: true },
    { order: 2, name: '选择样本', isshow: false, switch: true },
    { order: 3, name: '存入样本确认', isshow: false, switch: true },
    { order: 4, name: '样本核查', isshow: false, switch: true },
    { order: 5, name: '上传存档文件', isshow: true, switch: true, attribute: 'in' },
    { order: 6, name: '高拍仪拍摄', isshow: true, switch: true, attribute: 'in' },
    { order: 7, name: '电子签名', isshow: true, switch: true, attribute: 'in' },
  ],
  out: [
    { order: 1, name: '新建出库单', isshow: false, switch: true },
    { order: 2, name: '选择样本', isshow: false, switch: true },
    { order: 3, name: '取出样本确认', isshow: false, switch: true },
    { order: 4, name: '样本核查', isshow: false, switch: true },
    { order: 5, name: '上传存档文件', isshow: true, switch: true, attribute: 'out' },
    { order: 6, name: '高拍仪拍摄', isshow: true, switch: true, attribute: 'out' },
    { order: 7, name: '电子签名', isshow: true, switch: true, attribute: 'out' },
  ],
  Inventory: [
    { order: 1, name: '新建盘点单', isshow: false, switch: true },
    { order: 2, name: '选择样本', isshow: false, switch: true },
    { order: 3, name: '样本盘点确认', isshow: false, switch: true },
    { order: 4, name: '样本核查', isshow: false, switch: true },
    { order: 5, name: '上传存档文件', isshow: true, switch: true, attribute: 'Inventory' },
    { order: 6, name: '高拍仪拍摄', isshow: true, switch: true, attribute: 'Inventory' },
    { order: 7, name: '电子签名', isshow: true, switch: true, attribute: 'Inventory' },
  ],
});
const subdata: any = reactive({
  processName: '', //流程名称
  specimenType: '',
  dataLink: []
});
const enumeration = ['null', 'registration', 'in', 'out', 'a', 'b', 'c', 'Inventory'];
//提交
const submit = async () => {
  await dynamicFormRef.value?.validate();
  Modal.confirm({
    title: '确认保存吗?',
    onOk: async () => {
      Object.keys(tabdata).forEach(item => {
        subdata.dataLink.push({
          processType: enumeration.findIndex(el => el == item), //业务流程类型1:样本登记；2：样本入库；3：样本出库；4：样本移库；5：样本检测；6：样本分装；7：库存盘点
          isArchive: tabdata[item].find(el => el.name == '上传存档文件').switch,
          isCapture: tabdata[item].find(el => el.name == '高拍仪拍摄').switch,
          isSignature: tabdata[item].find(el => el.name == '电子签名').switch,
        })
      })
      if (id) {
        await getPutList(subdata, id);
      } else {
        await getAddList(subdata);
      }

      supertable.value?.refreshTable();
      onClose();
    },
    onCancel() {
      console.log('Cancel');
    },
  });
};
//提交
const submit2 = async () => {
  Modal.confirm({
    title: '确认保存吗?',
    onOk: async () => {
      let arr = [];
      targetKeys.value.forEach((item) => {
        dataSource.value.forEach((el) => {
          if (el.key == item) {
            arr.push(el);
          }
        });
      });
      subdata.specimenType = arr.map((item) => item.title).join('|');
      await getPutList(subdata, id);
      supertable.value?.refreshTable();
      onClose();
    },
    onCancel() {
      console.log('Cancel');
    },
  });
};

//状态改变
const switchChange = (arr) => {
  tabdata[arr[0]][arr[1] - 1].switch = arr[2];
};
// 配置样本类型部分
const tData: any = ref([]);
const dataSource: any = ref([]);
let searchArr: any = ref([]);
const getSampType = async (obj, row) => {
  dataSource.value = [];
  searchArr.value = [];
  const { result } = await gettypeList(obj);
  let specimenType = [];
  row?.specimenType ? (specimenType = row.specimenType.split('|')) : '';

  result.forEach((item) => {
    tData.value.push({ key: String(item.id), title: item.classify });
    if (item.value) {
      tData.value[tData.value.length - 1].children = [];
      item.value.split('|').forEach((el, i) => {
        if (specimenType.includes(el)) targetKeys.value.push(`${item.id}-${i}`);
        dataSource.value.push({ key: `${item.id}-${i}`, title: el, faid: item.id, fatitle: item.classify });
        searchArr.value.push({ key: `${item.id}-${i}`, title: el, faid: item.id, fatitle: item.classify });
        tData.value[tData.value.length - 1].children.push({ key: `${item.id}-${i}`, title: el, faid: item.id });
      });
    }
  });
};

function isChecked(selectedKeys: (string | number)[], eventKey: string | number) {
  return selectedKeys.indexOf(eventKey) !== -1;
}

function handleTreeData(treeNodes, targetKeys: string[] = []) {
  return treeNodes.map(({ children, ...props }) => ({
    ...props,
    disabled: targetKeys.includes(props.key as string),
    children: handleTreeData(children ?? [], targetKeys),
  }));
}
const targetKeys = ref<string[]>([]);
//数组去重
const removeDuplicate = (arr) => {
  for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i].key == arr[j].key) {
        //第一个等同于第二个，splice方法删除第二个
        arr.splice(j, 1);
        j--;
      }
    }
  }
  return arr;
};
const treeData = computed(() => {
  const result = removeDuplicate(searchArr.value.map((item) => ({ key: String(item.faid), title: item.fatitle })));
  result.forEach((el) => {
    el.children = [];
    searchArr.value.forEach((item) => {
      if (el.key == item.faid) {
        el.children.push({ key: item.key, title: item.title, faid: item.faid, fatitle: item.fatitle });
      }
    });
  });
  return handleTreeData(result, targetKeys.value);
});

const onChecked = (e, checkedKeys: string[], onItemSelect: (n: any, c: boolean) => void) => {
  const { eventKey, children } = e.node;
  if (children.length > 0) {
    children
      .map((item) => item.key)
      .forEach((el) => {
        onItemSelect(el, !isChecked(checkedKeys, el));
      });
  }
  onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
};
// 搜索

const filterOption = (inputValue, option) => {
  searchArr.value = [];
  dataSource.value.forEach((ul) => {
    if (ul.title.indexOf(inputValue) > -1) {
      searchArr.value.push(ul);
    }
  });
  return option.title.indexOf(inputValue) > -1;
};
const transferSearch = (direction, value) => {
  if (!value) {
    searchArr.value = dataSource.value;
  }
};
const transferChange = (targetKey, direction, moveKeys) => {
  if (direction == 'left') {
    let index = targetKeys.value.findIndex((item) => item == moveKeys.join('-')[0]);
    index != -1 ? targetKeys.value.splice(index, 1) : '';
  }
};
</script>
<style lang="less" scoped>
/deep/.ant-transfer {
  height: 100%;
}

/deep/.ant-transfer-list-body {
  overflow: auto;
}
</style>
